package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.base.BaseResult;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.model.CardBin;
import com.cardbaobao.cardbabyclient.model.result.CardBinResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.LoansUtils;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnFocusChange;
import butterknife.OnTextChanged;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/11 19:11.
 * 添加信用卡
 */

public class AddCreditCardActivity extends BaseActivity {
    public static final String PAGE_FROM_I="fromPage";
    public static final int PAGE_BANK_CARD_MANAGE=1;//银行卡管理页面
    public static final int PAGE_QUICK_DEBIT=2;//快捷收款页面
    private static final int TOTAL_COUNT_DOWN=60;
    private int mCountDown=0;
    private static final String TYPE_CREDIT_CARD="2";
    private static final String TYPE_DEBIT_CARD="1";

    public static final String NAME_S="name";//姓名
    public static final String ID_CARD_NO_S ="idCardNo";//身份证

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.et_card_number)
    EditText etCardNumber;
    @BindView(R.id.tv_real_name)
    TextView tvRealName;
    @BindView(R.id.tv_id_no)
    TextView tvIdNo;
    @BindView(R.id.et_valid_time)
    EditText etValidTime;
    @BindView(R.id.et_cvn2)
    EditText etCVN2;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_verify_code)
    EditText etVerifyCode;
    @BindView(R.id.bt_send_verify_code)
    Button btSendVerifyCode;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.tv_bank)
    TextView tvBank;

    @BindView(R.id.bt_ensure_commit)
    Button btEnsure;

    private String name;
    private String idCardNo;

    private String bankName;//银行名称
    private String bankCardId;//银行id
    private String bankCardLogo;//银行logo
    private String bankCardType;//银行卡类型

    private String phone;//手机号码，用于判断与接收验证码的手机号码是否一致
    private String verifyCode;

    private int fromPage;

    private Handler mHandler;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_credit_card;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ImmersionBar.with(this).keyboardEnable(true).init();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Intent intent = getIntent();

        mCurrentPageId=Self.Page.app_add_credit_card;

        name = intent.getStringExtra(NAME_S);
        idCardNo = intent.getStringExtra(ID_CARD_NO_S);
        fromPage=intent.getIntExtra(PAGE_FROM_I,0);

        if(!TextUtils.isEmpty(name)){
            //姓名*处理
            StringBuilder sb = new StringBuilder();
            for (int i = 0, length = name.length(); i < length; i++) {
                if (i == length - 1) {
                    sb.append(name.substring(i, i + 1));
                } else {
                    sb.append("*");
                }
            }
            tvRealName.setText(sb.toString());
        }
        if(!TextUtils.isEmpty(idCardNo)) {
            //身份证*处理
            StringBuilder sb = new StringBuilder();
            for (int i = 0, length = idCardNo.length(); i < length; i++) {
                if (i == length - 8 || i == length - 7 || i == length - 6 || i == length - 5) {
                    sb.append("*");
                } else {
                    sb.append(idCardNo.charAt(i));
                }
            }
            tvIdNo.setText(sb.toString());
        }

        mHandler=new Handler();
    }

    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName("添加信用卡");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    private Runnable countDownRunnable=new Runnable() {
        @Override
        public void run() {
            mCountDown--;
            if(mCountDown>0){
                btSendVerifyCode.setText(mCountDown+"s"+"重发");
                mHandler.postDelayed(this,Constant.ONE_SECOND);
            }else{
                btSendVerifyCode.setEnabled(true);
                btSendVerifyCode.setText("获取验证码");
            }
        }
    };

    //检查卡号
    private boolean checkCardNumber(){
        String text=etCardNumber.getText().toString().trim();
        if(text.length()==0){
            ToastUtil.showToast("请输入卡号");
            return false;
        }
        if(!RegularUtil.checkBankCard(text)){
            ToastUtil.showToast("信用卡格式不正确，请重新输入");
            return false;
        }
        return true;
    }

    //检查有效期
    private boolean checkValidTime(){
        String text=etValidTime.getText().toString().trim();
        if(text.length()==0){
            ToastUtil.showToast("请输入信用卡有效期");
            return false;
        }
        if(text.length()!=4){
            ToastUtil.showToast("有效期为4位数字");
            return false;
        }
        try{
            //检查月份
            int month=Integer.parseInt(text.substring(0,2));
            if(month>12||month<1){
                ToastUtil.showToast("月份错误，月份为01~12");
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            ToastUtil.showToast("信用卡有效期错误，请重新输入");
        }
        return true;
    }

    //检查cvn2
    private boolean checkCVN2(){
        String text=etCVN2.getText().toString().trim();
        if(text.length()==0||text.length()!=3){
            ToastUtil.showToast("请输入信用卡签名栏末三位");
            return false;
        }
        return true;
    }

    //检查手机号码
    private boolean checkPhoneNumber(){
        String text=etPhone.getText().toString().trim();
        if(text.length()==0){
            ToastUtil.showToast("请输入银行预留手机号");
            return false;
        }
        if(!RegularUtil.isPhoneNumber(text)){
            ToastUtil.showToast("手机号码格式不正确，请重新输入");
            return false;
        }
        if(!text.equals(phone)){
            ToastUtil.showToast("非法操作！");
            return false;
        }
        return true;
    }

    //检查验证码
    private boolean checkVerifyCode(){
        if(TextUtils.isEmpty(verifyCode)){
            ToastUtil.showToast("请获取验证码");
            return false;
        }
        String code=etVerifyCode.getText().toString();
        if(!verifyCode.equals(code)){
            ToastUtil.showToast("验证码错误，请重新输入");
            return false;
        }
        return true;
    }


    @OnFocusChange(R.id.et_card_number)
    public void onFocusChange(View view,boolean hasFocus){
        if(!hasFocus){
            String cardNumber=etCardNumber.getText().toString().trim();
            if(cardNumber.length()>0&&RegularUtil.checkBankCard(cardNumber)){
                queryCardBin(cardNumber,false);
            }
        }
    }

    @OnClick({R.id.bt_send_verify_code})
    public void onVerifyCodeClick(View view) {
        if (view.getId() == R.id.bt_send_verify_code) {
            showProgressDialog(false);
            btSendVerifyCode.setEnabled(false);
            //发送验证码
            final String code = String.valueOf(LoansUtils.getMsgCode());
            phone = etPhone.getText().toString();
            Api.sendSms(phone, Constant.VERIFY_CODE_TYPE, code, Constant.GDX030103).
                    subscribe(new Subscriber<String>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            dismissProgressDialog();
                            btSendVerifyCode.setEnabled(true);
                            ToastUtil.showToast(ApplicationHelper.
                                    getApplicationContext().
                                    getString(R.string.string_request_server_fail));
                        }

                        @Override
                        public void onNext(String s) {
                            dismissProgressDialog();
                            JSONObject json = JSONObject.parseObject(s);
                            if ("1".equals(json.getString("status"))) {
                                //验证码发送成功
                                verifyCode = code;
                                mCountDown = TOTAL_COUNT_DOWN;
                                mHandler.post(countDownRunnable);
                            } else {
                                //验证码发送失败
                                ToastUtil.showToast(json.getString("result"));
                            }

                        }
                    });
        }
    }

    @OnClick({R.id.bt_ensure_commit})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.bt_ensure_commit:
                //埋点
                SelfUtils.buriedClickData(Self.Action.app_click_add_credit_card_confirmadd,
                        Self.Action.app_click_add_credit_card_confirmadd_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);

                if(checkCardNumber()&&checkValidTime()&&checkCVN2()&&checkPhoneNumber()&&checkVerifyCode()){
                    showProgressDialog(false);
                    queryCardBin(etCardNumber.getText().toString().trim(),true);
                }
                break;
        }
    }

    private void queryCardBin(String cardNumber,final boolean showToast){
        Api.queryCardBin(cardNumber).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                if(showToast){
                    dismissProgressDialog();
                    ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }
            }

            @Override
            public void onNext(String s) {
                CardBinResult result= JsonUtil.json2Object(s,CardBinResult.class);
                if(result.getCode()== Constant.SUC_CODE){
                    //成功
                    CardBin bin=result.getData();
                    AddCreditCardActivity.this.bankCardType=bin.getBank_type();
                    AddCreditCardActivity.this.bankName=bin.getBank_name();
                    AddCreditCardActivity.this.bankCardId=bin.getBank_id();
                    AddCreditCardActivity.this.bankCardLogo=bin.getBank_logo();
                    if(TYPE_CREDIT_CARD.equals(AddCreditCardActivity.this.bankCardType)){
                        //信用卡
                        if(showToast){
                            //已经要提交数据了
                            Map<String,String> params=new HashMap<>();
                            params.put("member_id",String.valueOf(mApplication.getUser().getID()));
                            params.put("card_type_id",AddCreditCardActivity.this.bankCardId);
                            params.put("card_type_name",AddCreditCardActivity.this.bankName);
                            params.put("user_name",name);
                            params.put("mobile_no",phone);
                            params.put("id_card_no",idCardNo);
                            params.put("credit_card_no",etCardNumber.getText().toString().trim());
                            params.put("cvn2",etCVN2.getText().toString().trim());
                            String time=etValidTime.getText().toString().trim();
                            params.put("exp_year",time.substring(2));
                            params.put("exp_month",time.substring(0,2));
                            bindCreditCard(params);
                        }
                    }else{
                        if(showToast){
                            dismissProgressDialog();
                            if(TYPE_DEBIT_CARD.equals(AddCreditCardActivity.this.bankCardType)){
                                ToastUtil.showToast("请填写信用卡卡号");
                            }
                        }
                    }
                    if(TextUtils.isEmpty(AddCreditCardActivity.this.bankName)||
                            TextUtils.isEmpty(AddCreditCardActivity.this.bankCardType)){
                        tvBank.setText("");
                    }else{
                        tvBank.setText(AddCreditCardActivity.this.bankName+
                                " "+
                                (TYPE_CREDIT_CARD.equals(bankCardType)?"信用卡":"储蓄卡"));
                    }
                    if(TextUtils.isEmpty(AddCreditCardActivity.this.bankCardLogo)){
                        ivLogo.setImageResource(R.color.transparent);
                    }else{
                        ImageLoaderUtil.displayImageWithPlaceHolder(URLUtil.CBB_IMG_URL+AddCreditCardActivity.this.bankCardLogo,
                                ivLogo,
                                R.mipmap.img_default_square);
                    }
                }else{
                    if(showToast){
                        dismissProgressDialog();
                        ToastUtil.showToast(result.getMsg());
                    }
                }
            }
        });
    }

    private void bindCreditCard(Map<String,String> params){
        Api.bindCreditCard(params).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                BaseResult result= JsonUtil.json2Object(s,BaseResult.class);
                if(result.getCode()== Constant.SUC_CODE){
                    //绑卡成功
                    switch (fromPage){
                        case PAGE_BANK_CARD_MANAGE:
                            //银行卡管理页面进入
                            Intent debitRepaymentIntent=new Intent(AddCreditCardActivity.this,
                                    AddCreditCardSuccessActivity1.class);
                            debitRepaymentIntent.putExtra(PRE_PAGE_ID_S,
                                    mCurrentPageId);
                            startActivity(debitRepaymentIntent);
                            break;
                        case PAGE_QUICK_DEBIT:
                            //快捷收款页面进入(预添加信用卡页面)
                            Intent quickDebitIntent=new Intent(AddCreditCardActivity.this,
                                    AddCreditCardSuccessActivity.class);
                            quickDebitIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                            startActivity(quickDebitIntent);
                            break;
                            default:
                                ToastUtil.showToast("信用卡添加成功");
                                break;
                    }
                    finish();
                }else{
                    ToastUtil.showToast(result.getMsg());
                }
            }
        });
    }

    @OnTextChanged({R.id.et_phone})
    public void afterPhoneChanged(Editable s){
        if(s.length()>0&&RegularUtil.isPhoneNumber(s.toString())){
            if(mCountDown==0){
                btSendVerifyCode.setEnabled(true);
            }
            if(etCardNumber.length()>0&&etValidTime.length()>0&&etCVN2.length()>0&&etVerifyCode.length()>0){
                btEnsure.setEnabled(true);
            }else{
                btEnsure.setEnabled(false);
            }
        }else{
            btSendVerifyCode.setEnabled(false);
        }
    }

    @OnTextChanged({R.id.et_card_number,R.id.et_valid_time,R.id.et_cvn2,R.id.et_verify_code})
    public void afterTextChange(Editable s){
        if(etCardNumber.length()>0&&etValidTime.length()>0&&etCVN2.length()>0&&etPhone.length()>0&&etVerifyCode.length()>0){
            btEnsure.setEnabled(true);
        }else{
            btEnsure.setEnabled(false);
        }
    }
}
